#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

LTN* LTBuyNode(LTDataType x)
{
	LTN* newnode = (LTN*)malloc(sizeof(LTN));
	if (newnode == NULL) {
		perror("malloc fail!");
		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode->prev = newnode;

	return newnode;
}
LTN* LTInit()
{
	LTN* phead = LTBuyNode(-1);
	return phead;
}
void LTPushBack(LTN* phead, LTDataType x)
{
	assert(phead);
	LTN* newnode = LTBuyNode(x);
	newnode->prev = phead->prev;
	newnode->next = phead;

	phead->prev->next = newnode;
	phead->prev = newnode;
}
void LTPushFront(LTN* phead, LTDataType x)
{
	assert(phead);

	LTN* newnode = LTBuyNode(x);

	newnode->prev = phead;
	newnode->next = phead->next;

	phead->next->prev = newnode;
	phead->next = newnode;
}
void LTPopBack(LTN* phead)
{
	assert(phead);
	assert(phead->next != phead);

	/*phead->prev->prev->next = phead;
	phead->prev = phead->prev->prev;

	free(phead->prev);
	phead->prev = NULL;*/
	LTN* del = phead->prev;
	LTN* prev = del->prev;

	prev->next = phead;
	phead->prev = prev;

	free(del);
	del = NULL;
}
void LTPopFront(LTN* phead)
{
	assert(phead);
	assert(phead->next != phead);

	/*phead->next->next->prev = phead;
	phead->next = phead->next->next;

	free(phead->next);
	phead->next = NULL;*/
	LTN* del = phead->next;
	LTN* next = del->next;

	//phead del next
	next->prev = phead;
	phead->next = next;

	free(del);
	del = NULL;
}
LTN* LTFind(LTN* phead, LTDataType x)
{
	assert(phead);
	LTN* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void LTInsert(LTN* pos, LTDataType x)
{
	assert(pos);
	LTN* newnode = LTBuyNode(x);

	newnode->prev = pos;
	newnode->next = pos->next;

	pos->next->prev = newnode;
	pos->next = newnode;
}
void LTErase(LTN* pos)
{
	assert(pos);

	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
}
void LTPrint(LTN* phead)
{
	assert(phead);
	LTN* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}
void LTDesTroy(LTN* phead)
{
	assert(phead);
	LTN* pcur = phead->next;
	while (pcur != phead)
	{
		LTN* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}